package com.mjr.webmanage.interceptor;

import com.mjr.webmanage.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 令牌校验拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.info("拦截的请求：{}", url);
        if (url.contains("/login")) {
            log.info("----------->登录请求，放行");
            return true;
        }
        String token = request.getHeader("Token");
        // 令牌不存在 响应401
        if (!StringUtils.hasLength(token)) {
            log.info("----------->令牌不存在 ，响应401");
            response.setStatus(401);
            return false;
        }
        // 令牌存在，解析令牌
        try {
            JwtUtils.parseJWT(token);
            log.info("----------->令牌解析成功，放行");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("----------->令牌解析失败，响应401");
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
